import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, message, Input, Table, Form, Row, Col, Select, Space, Radio, InputNumber } from 'antd';
import PropTypes from 'prop-types';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';

const levelConfig = {
  0: '低',
  1: '中',
  2: '高',
}

const FormItem = Form.Item;
const { TextArea } = Input;
const mapStateToProps = (state: any) => ({
  batteryMonitorWarningVehicle: state.batteryMonitorWarningVehicle,
})
class DealModal extends PureComponent<any, any> {
  static contextTypes = {
    dicData: PropTypes.any
  };
  formRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    this.state = {
      formvalues: {},
      warningList: [],
    }
  }

  componentDidMount() {
    const { onRef } = this.props
    onRef && onRef(this);
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, vin } = this.props
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      this.getVehicleMsg(vin)
    }
  }

  //  查询预警车辆关联信息
  getVehicleMsg = (vin: string) => {
    const { dispatch } = this.props
    dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/battery/monitor/vehicle/order/prepare',
        vin,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          const { warningList, ...rest } = res.data;
          this.formRef.current && this.formRef.current.setFieldsValue({
            ...rest,
            orderLevelName: levelConfig[rest.orderLevel] || '',
          })
          this.setState({
            warningList: warningList
          })
        }
      }
    })
  }

  //  提交表单
  ok = (values: any) => {
    const { dispatch, refreshPage } = this.props
    const { warningList } = this.state
    const { vin, orderLevel, priority, recommendHandleWay, workItems  } = values
    const warningData = warningList.map((item: any) => {
      return {
        code: item.code,
        type: item.type,
        level: item.level,
        warningDate: item.warningDate,
      }
    })
    const data = {
      vin,
      level: orderLevel,
      priority,
      recommendHandleWay: recommendHandleWay * 1,
      workItems,
      warningList: warningData
    };
    dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/battery/monitor/vehicle/order/handle',
        ...data,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('操作成功');
          this.close();
          refreshPage();
        }
      },
    });
  }

  handleDeal = () => {
    this.formRef.current?.submit();
  }

  close = () => {
    const { closeModal } = this.props;
    this.formRef.current && this.formRef.current.resetFields();
    this.setState({
      warningList: []
    })
    closeModal();
  }

  render() {
    const { modalVisible } = this.props;
    const { warningList } = this.state
    const loading = false
    const handleWay = getDictOptionsByCode(this.context.dicData, 'recommendHandleWay');
    const columns = [
      {
        title: '预警编号',
        dataIndex: 'code',
      },
      {
        title: '交付日期',
        dataIndex: 'enrollDate',
      },
      {
        title: '累计里程（KM）',
        dataIndex: 'accruedMiles',
      },
      {
        title: '风险等级',
        dataIndex: 'level',
        render: (text: any) => {
          return text == 2 ? '高' : text == 1 ? '中' : text == 0 ? '低' : '';
        }
      },
      {
        title: '预警时间',
        dataIndex: 'warningDate',
      },
      {
        title: '故障预警类型',
        dataIndex: 'type',  //  预警类型，待大数据确定
        render: (text: any) => {
          return getDicByKey(this.context.dicData, 'faultType', text + '');
        }
      },
    ]

    const footer = (
      <div>
        <Button onClick={this.close}>
          取消
        </Button>
        <Button loading={loading} onClick={this.handleDeal} type="primary">
          保存
        </Button>
      </div>
    )

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };

    return (
      <Modal
        title="预警处理"
        footer={footer}
        visible={modalVisible}
        width={850}
        onCancel={this.close}
      >
        <Form style={{ marginTop: 12 }} 
          ref={this.formRef}
          onFinish={this.ok}
          initialValues={{
            priority: 2,
          }}
        >
          <Row gutter={24}>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="vin"
                label="VIN码"
              >
                <Input disabled={true} placeholder="" />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="brandName"
                label="品牌"
              >
                <Input disabled={true} placeholder="" />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="seriesName"
                label="车系"
              >
                <Input disabled={true} placeholder="" />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="typeName"
                label="车型"
              >
                <Input disabled={true} placeholder="" />
              </FormItem>
            </Col>
            <Col span={12}>
              <Form.Item name="orderLevel" noStyle>
                <Input type="hidden" />
              </Form.Item>
              <FormItem
                {...formItemLayout}
                name="orderLevelName"
                label="风险等级"
              >
                <Input disabled={true} placeholder="" />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="batteryType"
                label="电池类型"
              >
                <Input disabled={true} placeholder="" />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="batterySupplier"
                label="电池供应商"
              >
                <Input disabled={true} placeholder="" />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="batteryCode"
                label="电池包编号"
              >
                <Input disabled={true} placeholder="" />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="priority"
                label="优先级"
                rules={[{ required: true, message: '请选择优先级！' }]}
              >
                <Select
                  // allowClear
                  placeholder="请选择"
                  optionFilterProp="children"
                  // defaultValue={2}
                  options={[
                    {
                      value: 0,
                      label: '低',
                    },
                    {
                      value: 1,
                      label: '中',
                    },
                    {
                      value: 2,
                      label: '高',
                    },
                  ]}
                >
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                name="recommendHandleWay"
                label="建议处理方式"
                rules={[{ required: true, message: '请选择建议处理方式！' }]}
              >
                <Select
                  // allowClear
                  placeholder="请选择"
                  optionFilterProp="children"
                  options={handleWay}
                >
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <FormItem
                labelCol={{
                  xs: { span: 24 },
                  sm: { span: 4 },
                  md: { span: 4 },
                }}
                wrapperCol={{
                  xs: { span: 24 },
                  sm: { span: 20 },
                  md: { span: 20 },
                }}
                label="工作事项"
                name="workItems"
                rules={[
                  { required: true, message: '请输入工作事项！', },
                  { max: 1000, message: '工作事项不能多于1000个字符' }
                ]}
              >
                <TextArea rows={3} placeholder="请输入" />
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div>
          <p>未处理预警（{warningList ? warningList.length : 0}）</p>
          <Table
            columns={columns}
            dataSource={warningList || []}
            pagination={false}
            bordered
          ></Table>
        </div>
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(DealModal);
